package ServiceProvider;

import java.net.*;
import java.util.*;

import DataCenter.ConfigAccessor;

import java.io.*;

public class QueryHandler extends Thread {

	private static final String QUERY_CONTENT_1 = "Topics";
	private static final String QUERY_CONTENT_2 = "HostNetwork";
	private static final int DELAY_TIME = 10000;
	
	private boolean ifStopThread = true;
	
	private Socket socket;
	private BufferedReader queryReader;
	private PrintWriter queryResponer;
	private String name;

	public QueryHandler(String name, Socket socket) {
		this.socket = socket;
		this.name = name;
		try {
			queryReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			queryResponer = new PrintWriter(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		while (ifStopThread) {
			try {
				String received = queryReader.readLine();
				if (received == null)
					break;

				if (received.equals("Feed")) {
					queryResponer.println("Back");
					queryResponer.flush();
				} else if (received.equals(QUERY_CONTENT_1)) {
					this.respondQueryWithResult(ConfigAccessor.sharedInstance().getTopicNameSet().toString());
				} else if (received.equals(QUERY_CONTENT_2)) {
					this.respondQueryWithResult(ConfigAccessor.sharedInstance().getSelfInfo().toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		// loop end and close relative resource
		try {
			queryResponer.close();
			queryReader.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void respondQueryWithResult(final String result) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				queryResponer.println(name + ":" + result);
				queryResponer.flush();
				ifStopThread = false;
			}
		}, DELAY_TIME);
	}
	
}
